<template>
  <div class="container">
    <p class="header">请选择支付方式</p>
    <!-- 支付宝支付 -->
    <van-radio-group v-model="checked">
      <div class="zhifubao">
        <p>
          <van-radio name="a" checked-color="#ee0a24"></van-radio>
        </p>
        &nbsp;&nbsp;&nbsp;
        <p>
          <van-icon name="alipay" color="#00a1e9" size="40" />
        </p>
        <p>&nbsp;&nbsp;&nbsp;支付宝</p>
      </div>
      <van-divider />
      <!-- 微信支付 -->
      <div class="wx">
        <p>
          <van-radio name="b" checked-color="#ee0a24"></van-radio>
        </p>
        &nbsp;&nbsp;&nbsp;
        <p>
          <van-icon name="wechat" color="#00c901" size="40" />
        </p>
        <p>&nbsp;&nbsp;&nbsp;微信支付</p>
      </div>
    </van-radio-group>
    <van-button size="large" color="#b4282d" @click="toPay">确定</van-button>

    <!-- 弹出支付框 -->
    <van-dialog
      v-model:show="show"
      title="立即支付"
      show-cancel-button
      @confirm="isPay('confirm')"
      @cancel="isPay('cancel')"
    >
      <img style="display: block; margin: auto" :src="imgSrc" />
    </van-dialog>
  </div>
</template>

<script lang="ts" setup>
// import { reqCreateNative } from '@/api/pay'
// import { watch } from 'vue'
import { reqCreateNative, reqPayStatus } from '@/api/pay'
import { onMounted, ref } from 'vue'
import { useRoute } from 'vue-router'
import QRCode from 'qrcode'
import { useRouter } from 'vue-router'

const router = useRouter()

const checked = ref('a')

// 支付方式单选按钮

const show = ref(false)
// 定义二维码路径
const imgSrc = ref()

// orderId
const route = useRoute()
// 存储支付信息
const payInfo = ref()

// 获取支付二维码的方法
const getPayImg = async () => {
  const res = await reqCreateNative(route.query.orderId)
  if (res.code === 200) {
    // console.log(res)
    payInfo.value = res.data
  }
}

// 点击是否支付
const isPay = async (type) => {
  if (type === 'confirm') {
    // 调接口判断是否支付成功
    const res = await reqPayStatus(route.query.orderId)
    if (res.code === 200) {
      // 支付成功，跳转到订单列表
      router.push('/orderlist')
    } else {
      // 请支付
    }
  } else {
    // 取消支付
  }
}

// 点击支付
const toPay = async () => {
  // console.log(payInfo.value.codeUrl)

  await getPayImg()
  //    // 能够将文字、链接转换成图片
  const srcUrl = await QRCode.toDataURL(payInfo.value.codeUrl)
  imgSrc.value = srcUrl
  show.value = true
}

onMounted(() => {
  console.log(route.query.orderId)
})
</script>

<script lang="ts">
export default {
  name: 'VPaying'
}
</script>

<style lang="scss" scoped>
.header {
  padding: 20px 20px 10px;
  margin: 0;
  font-size: 0.1rem;
}

.zhifubao,
.wx {
  padding: 10px;
  background-color: #ffffff;
  height: 30px;
  line-height: 30px;
  display: flex;
  justify-content: left;
  align-items: center;
  p {
    font-size: 0.4rem;
    font-weight: 700;
    margin: 0;
  }
}

.van-divider {
  margin: 0;
}

.van-button {
  position: fixed;
  bottom: 0px;
  z-index: 999;
}
</style>
